#include <Arduino.h>
#include <TimeLib.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <ESP8266WiFi.h>      //8266连接wifi库
#define FS_NO_GLOBALS         // 调用ESP8266的SPIFFS FLASH
#include <FS.h>
#include <ArduinoJson.h>      //json解析库
#include <WiFiManager.h>  
#include <ESP8266WiFiMulti.h>
#include <MQTTPubSubClient.h>
WiFiUDP ntpUDP; 
NTPClient timeClient(ntpUDP, "pool.ntp.org", 60*60*8,30*60*1000);

const char* host = "api.seniverse.com";     // 将要连接的服务器地址  
const int httpPort = 80;                    // 将要连接的服务器端口 
     
const char* ssid     = "*****";             // 连接WiFi名
const char* password = "***********";      // WIFI密码

//心知天气HTTP请求所需信息
String reqUserKey = "************";    // 心知天气私钥
String reqLocation = "********";           // 城市拼音
String reqUnit = "c";                       // 摄氏

int tmp;
int hours ;
int minutes ;
int seconds ;
int weekDay ;
int monthDay ;
int currentMonth ;
String data1 = "";
void TimeGet(){
  timeClient.update();
  hours = timeClient.getHours();
  minutes = timeClient.getMinutes();
  seconds = timeClient.getSeconds();
  }


void setup() {
  Serial.begin(115200); //初始化串口
  while(Serial.read() >= 0){}//清除串口缓冲区
  connectWiFi();
}

String readLine()//读整行字符串子程序
{
  String comdata ="";
  while(Serial.available())
  {
    comdata += char(Serial.read());
    delay(2);
  }
return comdata;
}

String readdata = "";

void loop() {
    //NTP服务获取时间信息
    timeClient.update();
    unsigned long epochTime = timeClient.getEpochTime();
    hours = timeClient.getHours();
    minutes = timeClient.getMinutes();
    seconds = timeClient.getSeconds();
    weekDay = timeClient.getDay();
    struct tm *ptm = gmtime((time_t *)&epochTime);
    monthDay = ptm->tm_mday;
    currentMonth = ptm->tm_mon + 1;

    //建立心知天气API当前天气请求资源地址
    String reqRes =   "/v3/weather/now.json?key=" + reqUserKey +
                  + "&location=" + reqLocation + 
                    "&language=en&unit=" +reqUnit;
                  
    //向心知天气服务器服务器请求信息并对信息进行解析
    httpRequest(reqRes);
    
    //数据获取间隔 1s
    delay(1000);

    //获取时间
    TimeGet();
  
    readdata  =  readLine();     //将分立的单个数据转化为字符后连接起来

    int test_num = strcmp(readdata.c_str(),"DATA") ;
    int test_num_1 = strcmp(readdata.c_str()," DATA") ;     //strcmp函数判断两个字符串相等返回值为13
    /*if(strcmp(readdata.c_str(),"WIFI") == 13)             //有数据才显示
    {
     
     //WiFi.begin(ssid, password);
     //timeClient.begin();
     Serial.println("WiFi connected!");
     readdata = "";
    } */
    
    if(test_num == 13 || test_num_1 == 13)             //strcmp函数判断两个字符串相等返回值为13
    {
     if((tmp != 0) && (currentMonth > 1)){
     Serial.printf("#h%d,m%d,s%d,t%d,m%d,d%d,w%d*",hours,minutes,seconds,tmp,currentMonth,monthDay,weekDay);
     Serial.println("");
     readdata = ""; 
    }
    else{
      }  
    }
    readdata = "";                     //清空数据缓存
  }
  
// 向心知天气服务器服务器请求信息并对信息进行解析
void httpRequest(String reqRes){
  WiFiClient client;
  // 建立http请求信息
  String httpRequest = String("GET ") + reqRes + " HTTP/1.1\r\n" + 
                              "Host: " + host + "\r\n" + 
                              "Connection: close\r\n\r\n";
  // 尝试连接服务器
  if (client.connect(host, 80)){
    // 向服务器发送http请求信息
    client.print(httpRequest); 
    // 获取并显示服务器响应状态行 
    String status_response = client.readStringUntil('\n');
    // 使用find跳过HTTP响应头
    if (client.find("\r\n\r\n")) {}
    // 利用ArduinoJson库解析心知天气响应信息
    parseInfo(client); 
  } 
  else {
  }   
    //断开客户端与服务器连接工作
    client.stop(); 
}

// 连接WiFi
void connectWiFi(){
  WiFi.begin(ssid, password);                  // 启动网络连接
  while (WiFi.status() != WL_CONNECTED){
    delay(1000);
  }
  timeClient.begin();
}
int tmp_f = 0;
// 利用ArduinoJson库解析心知天气响应信息
void parseInfo(WiFiClient client){
  const size_t capacity = JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(1) + 
                        2*JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(6) + 230;
  DynamicJsonDocument doc(capacity);
  deserializeJson(doc, client);
  JsonObject results_0 = doc["results"][0];
  JsonObject results_0_now = results_0["now"];
  const char* results_0_now_text = results_0_now["text"]; // "Sunny"
  const char* results_0_now_code = results_0_now["code"]; // "0"
  const char* results_0_now_temperature = results_0_now["temperature"]; // "32"
  const char* results_0_last_update = results_0["last_update"]; // "2020-06-02T14:40:00+08:00"

  String results_0_now_text_str = results_0_now["text"].as<String>(); 
  int results_0_now_code_int = results_0_now["code"].as<int>(); 
  int results_0_now_temperature_int = results_0_now["temperature"].as<int>(); 
  String results_0_last_update_str = results_0["last_update"].as<String>(); 
    
  int sdata = results_0_now_code_int*100 + results_0_now_temperature_int;

  if(sdata == 0){
    tmp = tmp_f;
    }
    else{
     tmp = sdata;
     tmp_f = tmp;
    }
}
